package edu.hebtu.controller;

import edu.hebtu.mapper.impl.*;
import edu.hebtu.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

@Controller
public class AppointmentController {

    private final UserMapper userMapper;
    private final CarMapper carMapper;
    private final DistributionMapper distributionMapper;
    private final AppointmentMapper appointmentMapper;
    private final TimeSlotMapper timeSlotMapper;
    private final SubjectMapper subjectMapper;
    private final ScoreMapper scoreMapper;

    @Autowired
    public AppointmentController(UserMapper userMapper,
                             CarMapper carMapper,
                             DistributionMapper distributionMapper,
                             AppointmentMapper appointmentMapper,
                             TimeSlotMapper timeSlotMapper,
                             SubjectMapper subjectMapper,
                                 ScoreMapper scoreMapper) {
        this.userMapper = userMapper;
        this.carMapper = carMapper;
        this.distributionMapper = distributionMapper;
        this.appointmentMapper = appointmentMapper;
        this.timeSlotMapper = timeSlotMapper;
        this.subjectMapper = subjectMapper;
        this.scoreMapper = scoreMapper;
    }

    @RequestMapping("/exercise_carAppointmentInfo")
    public String exercise_carAppointmentInfo(Model model, HttpSession session) {
        User user = userMapper.findById(((User) session.getAttribute("user")).getUserId()).get(0);
        List<Distribution> distributions = distributionMapper.findByUserId(user.getUserId());       //找到学员所分配的教练
        List<Score> scores = scoreMapper.findById(null);
        scores.removeIf(aValue -> !aValue.getUserId().equals(user.getUserId()));         //找到学员的成绩信息
        List<Car> cars = carMapper.findById(null);          //查找所有车辆信息
        boolean flag;
        for (Iterator<Car> carIterator = cars.iterator(); carIterator.hasNext(); ) {        //去掉不是该学员的教练所属的车辆
            Car car = carIterator.next();
            flag = false;
            for (Distribution distribution : distributions) {
                if (distribution.getCoachId().equals(car.getCustodian())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) carIterator.remove();
            else {
                User user1 = userMapper.findById(car.getCustodian()).get(0);            //找到车辆其负责的教练
                Subject subject = subjectMapper.findById(user1.getSubjectId()).get(0);          //找到教练所教授的科目信息
                car.setCustodian(user1.getName() + "(" + subject.getSubjectName() + " / " + user1.getPhone() + ")");
                for (Score score : scores) {
                    if (score.getSubjectId().equals(subject.getSubjectId())) {          //找到该科目的成绩信息
                        if (subject.getPassLine() <= score.getScore()) {            //学员的成绩大于等于及格线时为通过考试，即不能再预约考试
                            car.setState("该科目已通过考试");
                            break;
                        }
                    }
                }
                if (car.getState().trim().equals("appear")) car.setState("正常");
                if (car.getState().trim().equals("repair")) car.setState("修理中");
                if (user.getState().equals("licenced")) car.setState("学员已拿证");
            }
        }
        List<Car> cars1 = carMapper.findById(null);
        for (Distribution distribution : distributions) {
            flag = false;
            for (Car car : cars1) {
                if (distribution.getCoachId().equals(car.getCustodian())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                Car car = new Car();
                User user1 = userMapper.findById(distribution.getCoachId()).get(0);
                car.setState("尚未分配车辆");
                car.setCustodian(user1.getName() + "(" + subjectMapper.findById(user1.getSubjectId()).get(0).getSubjectName() + " / " + user1.getPhone() + ")");
                cars.add(car);
            }
        }
        model.addAttribute("cars", cars);
        return "tables/table-car-appointment";
    }

    @RequestMapping("/exerciseCarAppointment/{carId}")
    public String exerciseCarAppointment(@PathVariable("carId") String carId, Model model) {

        int n = 3;          //包括今天的连续n天可以预约

        model.addAttribute("carId", carId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");   //格式化日期时间
        SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("HH:mm");
        Calendar calendar = Calendar.getInstance();
        List<TimeSlot> timeSlots = timeSlotMapper.findById(null);
        List<StringCalendar> stringCalendars = new ArrayList<StringCalendar>();
        for (TimeSlot timeSlot : timeSlots) {
            String [] strTime = simpleTimeFormat.format(timeSlot.getStartTime()).split(":");
            Calendar time = Calendar.getInstance();
            time.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strTime[0]));
            time.set(Calendar.MINUTE, Integer.parseInt(strTime[1]));
            if (calendar.compareTo(time) > 0) {
                timeSlot.setState("timeOut");
            } else {
                time.set(Calendar.HOUR_OF_DAY, 0);
                time.set(Calendar.MINUTE, 0);
                time.set(Calendar.SECOND, 0);
                time.set(Calendar.MILLISECOND, 0);
                List<Appointment> appointments = appointmentMapper.findById(null);
                //移除预约信息中不是指定车辆以及不是该时间段的信息
                appointments.removeIf(aValue -> !aValue.getCarId().equals(carId) || !aValue.getTimeSlotId().equals(timeSlot.getTimeSlotId()));
                for (Appointment appointment : appointments) {
                    Calendar appointCalendar = Calendar.getInstance();
                    appointCalendar.setTime(appointment.getAppointmentDate());
                    appointCalendar.set(Calendar.HOUR_OF_DAY, 0);
                    appointCalendar.set(Calendar.MINUTE, 0);
                    appointCalendar.set(Calendar.SECOND, 0);
                    appointCalendar.set(Calendar.MILLISECOND, 0);
                    if (time.compareTo(appointCalendar) == 0) {
                        timeSlot.setState("reserved");
                        break;
                    }
                }
            }
        }
        stringCalendars.add(new StringCalendar(0, simpleDateFormat.format(calendar.getTime()), timeSlots));

        for (int i = 1 ; i < n ; i++) {
            timeSlots = timeSlotMapper.findById(null);
            calendar.add(Calendar.DATE, 1);
            for (TimeSlot timeSlot : timeSlots) {
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                List<Appointment> appointments = appointmentMapper.findById(null);
                //移除预约信息中不是指定车辆以及不是该时间段的信息
                appointments.removeIf(aValue -> !aValue.getCarId().equals(carId) || !aValue.getTimeSlotId().equals(timeSlot.getTimeSlotId()));
                for (Appointment appointment : appointments) {
                    Calendar appointCalendar = Calendar.getInstance();
                    appointCalendar.setTime(appointment.getAppointmentDate());
                    appointCalendar.set(Calendar.HOUR_OF_DAY, 0);
                    appointCalendar.set(Calendar.MINUTE, 0);
                    appointCalendar.set(Calendar.SECOND, 0);
                    appointCalendar.set(Calendar.MILLISECOND, 0);
                    if (calendar.compareTo(appointCalendar) == 0) {
                        timeSlot.setState("reserved");
                        break;
                    }
                }
            }

            stringCalendars.add(new StringCalendar(i, simpleDateFormat.format(calendar.getTime()), timeSlots));
        }

        model.addAttribute("stringCalendars", stringCalendars);

        return "pages/pages-user-appointment";
    }

    @RequestMapping("/editExerciseAppointment/{timeSlotId}/{carId}/{flag}")
    public String editExerciseAppointment(@PathVariable String timeSlotId, @PathVariable String carId, @PathVariable int flag, HttpSession session, Model model) {
        Calendar calendarNow = Calendar.getInstance();          //现在的日期
        Calendar lockCalendar = Calendar.getInstance();         //六点整
        lockCalendar.set(Calendar.HOUR_OF_DAY, 6);
        lockCalendar.set(Calendar.MINUTE, 0);
        lockCalendar.set(Calendar.SECOND, 0);
        lockCalendar.set(Calendar.MILLISECOND, 0);
        if (calendarNow.compareTo(lockCalendar) < 0) {
            model.addAttribute("result", "close");
            return "pages/pages-user-appointment-success";       //不到六点整不开放预约
        }
        User user = userMapper.findById(((User) session.getAttribute("user")).getUserId()).get(0);
        List<Appointment> appointments = appointmentMapper.findById(null);
        appointments.removeIf(aValue -> !aValue.getUserId().equals(user.getUserId()));
        if (appointments.size() > 0) {
            calendarNow.set(Calendar.HOUR_OF_DAY, 0);
            calendarNow.set(Calendar.MINUTE, 0);
            calendarNow.set(Calendar.SECOND, 0);
            calendarNow.set(Calendar.MILLISECOND, 0);
            calendarNow.add(Calendar.DATE, flag);
            for (Appointment appointment : appointments) {
                Calendar calendar1 = Calendar.getInstance();
                calendar1.setTime(appointment.getAppointmentDate());
                calendar1.set(Calendar.HOUR_OF_DAY, 0);
                calendar1.set(Calendar.MINUTE, 0);
                calendar1.set(Calendar.SECOND, 0);
                calendar1.set(Calendar.MILLISECOND, 0);
                if (calendarNow.compareTo(calendar1) == 0) {
                    model.addAttribute("result", "repair");         //每人每天只能预约一个时间段
                    return "pages/pages-user-appointment-success";
                }
            }
        }
        Appointment appointment = new Appointment();
        appointment.setUserId(userMapper.findById(((User) session.getAttribute("user")).getUserId()).get(0).getUserId());
        List<User> users = userMapper.findById(null);
        Car car = carMapper.findById(carId).get(0);                         //查找指定车辆的管理人
        users.removeIf(aValue -> !aValue.getUserId().equals(car.getCustodian()));       //通过车辆管理人找到科目信息subjectId
        appointment.setSubjectId(users.get(0).getSubjectId());
        appointment.setTimeSlotId(timeSlotId);
        appointment.setCarId(carId);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, flag);
        appointment.setAppointmentDate(calendar.getTime());

        appointmentMapper.add(appointment);         //将信息填入表中

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");             //格式化显示预约的时间
        SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("HH:mm");
        TimeSlot timeSlot = timeSlotMapper.findById(appointment.getTimeSlotId()).get(0);
        String timeSlotInfo = simpleDateFormat.format(appointment.getAppointmentDate()) + " " + simpleTimeFormat.format(timeSlot.getStartTime());
        timeSlotInfo += " - " + simpleTimeFormat.format(timeSlot.getEndTime());

        model.addAttribute("timeSlotInfo", timeSlotInfo);
        model.addAttribute("result", "success");

        return "pages/pages-user-appointment-success";
    }

    @RequestMapping("/appointment_Info")
    public String appointment_Info(Model model, HttpSession session) {
        User user = userMapper.findById(((User) session.getAttribute("user")).getUserId()).get(0);
        List<Appointment> appointments = appointmentMapper.findById(null);
        for (Iterator<Appointment> appointmentIterator = appointments.iterator(); appointmentIterator.hasNext(); ) {
            Appointment appointment = appointmentIterator.next();
            if (user.getUserId().equals(appointment.getUserId())) {        //筛选出该学员的预约信息
                TimeSlot timeSlot = timeSlotMapper.findById(appointment.getTimeSlotId()).get(0);
                Calendar now = Calendar.getInstance();      //当前的时间
                now.set(Calendar.SECOND, 0);                //秒和毫秒清零
                now.set(Calendar.MILLISECOND, 0);
                Calendar time = Calendar.getInstance();
                Calendar startTime = Calendar.getInstance();
                startTime.setTime(timeSlot.getStartTime());             //时间段的开始时间（时和分）
                time.setTime(appointment.getAppointmentDate());                     //预约的日期，不包括时间
                time.set(Calendar.SECOND, 0);               //秒和毫秒清零
                time.set(Calendar.MILLISECOND, 0);
                time.set(Calendar.HOUR_OF_DAY, startTime.get(Calendar.HOUR_OF_DAY));    //预约的日期加上预约时间段开始的时和分
                time.set(Calendar.MINUTE, startTime.get(Calendar.MINUTE));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");   //格式化日期时间
                String timeStr = simpleDateFormat.format(time.getTime()) + " - ";
                if (time.compareTo(now) < 0) {      //去掉预约的日期在当前时间之前的信息
                    appointmentMapper.delete(appointment);
                    appointmentIterator.remove();
                } else {
                    Calendar endTime = Calendar.getInstance();
                    endTime.setTime(timeSlot.getEndTime());             //时间段的结束
                    time.set(Calendar.HOUR_OF_DAY, endTime.get(Calendar.HOUR_OF_DAY));    //预约的日期加上预约时间段结束的时和分
                    time.set(Calendar.MINUTE, endTime.get(Calendar.MINUTE));
                    timeStr += simpleDateFormat.format(time.getTime());
                    appointment.setTimeSlotId(timeStr);                 //获取预约的时间段（年月日时分）
                    appointment.setCarId(carMapper.findById(appointment.getCarId()).get(0).getId() + "号车(" + carMapper.findById(appointment.getCarId()).get(0).getLicense() + ")"); //获取车牌号
                    appointment.setSubjectId(subjectMapper.findById(appointment.getSubjectId()).get(0).getSubjectName());   //获取科目名称
                }
            }
        }

        model.addAttribute("appointments", appointments);
        return "tables/table-user-appointment";
    }

    @RequestMapping("/user_deleteAppointment/{appointmentId}")
    public String user_deleteAppointment(@PathVariable("appointmentId") String appointmentId, Model model) {
        Appointment appointment = appointmentMapper.findById(appointmentId).get(0);

        appointment.setCarId(carMapper.findById(appointment.getCarId()).get(0).getId() + "号车(" + carMapper.findById(appointment.getCarId()).get(0).getLicense() +  ")"); //获取车牌号

        appointment.setSubjectId(subjectMapper.findById(appointment.getSubjectId()).get(0).getSubjectName());                       //获取科目名称

        TimeSlot timeSlot = timeSlotMapper.findById(appointment.getTimeSlotId()).get(0);
        Calendar time = Calendar.getInstance();
        Calendar startTime = Calendar.getInstance();
        startTime.setTime(timeSlot.getStartTime());             //时间段的开始时间（时和分）
        time.setTime(appointment.getAppointmentDate());                     //预约的日期，不包括时间
        time.set(Calendar.HOUR_OF_DAY, startTime.get(Calendar.HOUR_OF_DAY));    //预约的日期加上预约时间段开始的时和分
        time.set(Calendar.MINUTE, startTime.get(Calendar.MINUTE));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");   //格式化日期时间
        String timeStr = simpleDateFormat.format(time.getTime()) + " - ";
        Calendar endTime = Calendar.getInstance();
        endTime.setTime(timeSlot.getEndTime());             //时间段的结束
        time.set(Calendar.HOUR_OF_DAY, endTime.get(Calendar.HOUR_OF_DAY));    //预约的日期加上预约时间段结束的时和分
        time.set(Calendar.MINUTE, endTime.get(Calendar.MINUTE));
        timeStr += simpleDateFormat.format(time.getTime());
        appointment.setTimeSlotId(timeStr);                                                                                         //获取预约的时间段（年月日时分）

        model.addAttribute("appointment", appointment);
        return "delete/delete-user-appointment";
    }

    @RequestMapping("/deleteUserAppointment")
    public String deleteUserAppointment(Appointment appointment) {
        appointmentMapper.delete(appointment);
        return "redirect:/appointment_Info";
    }

}
